package com.quan.sso.client.filter;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.quan.common.base.pojo.HttpResult;
import com.quan.common.utils.HttpHelper;
import com.quan.sso.common.pojo.SSOUser;

public class TokenManager {
	
	static Logger logger = LoggerFactory.getLogger(TokenManager.class);

	// 业务系统与SSO系统间通信的内网地址
	static String serverInnerAddress;

	private TokenManager() {
	}

	/**
	 * 验证token的有效性
	 * 
	 * @param token
	 * @return
	 * @throws IOException
	 */
	public static SSOUser validate(String token) throws Exception {
		return remoteValidate(token);
	}

	/**
	 * 远程验证token有效性
	 * 
	 * @param token
	 * @return
	 * @throws IOException
	 */
	private static SSOUser remoteValidate(String token) throws Exception {
		String validateUrl = serverInnerAddress + "/api/sso/validate?token=" + token;
		HttpResult result = HttpHelper.executeGet(validateUrl);

		SSOUser user = null;

		if (result.getStatusCode() == 404) {
			throw new Exception("远程验证token失败，请检查URL是否正确：" + validateUrl);
		}

		if (result.getStatusCode() == 200) {
			String content = result.getContent();
			user = JSON.parseObject(content, SSOUser.class) ;
		}
		return user;
	}
}
